package com.midea.leetcode;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: Mr.Wang
 * @Description:使用LinkedHashMap取巧实现LRU算法
 * @Date: Create in 13:57 2021/10/30
 */
public class LRUDemo<K,V> extends LinkedHashMap<K,V>{
    private int capacity;//缓存坑位

    /**
     * 如果设置了 accessOrder = true 时，则每次使用 key 时（put 或者 get 时），都将 key 对应的数据移动到队尾（右边），表示这是最近经常使用的节点
     * 当 accessOrder = false 时，key 的顺序为插入双向链表时的顺序
     */
    public LRUDemo(int capacity) {
        super(capacity,0.75F,true);
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return super.size() > capacity;
    }

    public static void main(String[] args) {
        LRUDemo lruCacheDemo = new LRUDemo(3);
        lruCacheDemo.put(1,"a");
        lruCacheDemo.put(2,"b");
        lruCacheDemo.put(3,"c");
        System.out.println(lruCacheDemo.keySet());

        lruCacheDemo.put(4,"d");
        System.out.println(lruCacheDemo.keySet());

        lruCacheDemo.put(3,"c");
        System.out.println(lruCacheDemo.keySet());
        lruCacheDemo.put(3,"c");
        System.out.println(lruCacheDemo.keySet());
        lruCacheDemo.put(3,"c");
        System.out.println(lruCacheDemo.keySet());
        lruCacheDemo.put(5,"e");
        System.out.println(lruCacheDemo.keySet());
    }
}
